package com.web.weixin.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.web.weixin.kit.SecurityKit;
import com.web.weixin.msg.MessageKit;


@Controller
public class WechatController {
	public static final String TOKEN="weixin";
	
	@RequestMapping(value="/wxget",method=RequestMethod.GET)
	public void init(HttpServletRequest req,HttpServletResponse resp) throws IOException{
		String signature=req.getParameter("signature");
		String timestamp=req.getParameter("timestamp");
		String nonce=req.getParameter("nonce");
		String echostr=req.getParameter("echostr");
		String [] arr={WechatController.TOKEN,timestamp,nonce};
		Arrays.sort(arr);
		StringBuffer sb=new StringBuffer();
		for(String a:arr){
			sb.append(a);
		}
		String sha1=SecurityKit.sha1(sb.toString());
		if(sha1.equals(signature)){
			System.out.println(sha1.equals(signature));
			resp.getWriter().print(echostr);
		}
	}
	
	@RequestMapping(value="/wxget",method=RequestMethod.POST)
	public void getPost(HttpServletRequest req,HttpServletResponse resp) throws IOException{
		Map<String,String>msg=new HashMap<String,String>();
		msg=MessageKit.reqMsg2Map(req);
		System.out.println(msg.toString());
		String respMsg=MessageKit.handlerMsg(msg);
		System.out.println(respMsg);
		resp.setHeader("Content-Type", "application/xml");
		resp.setContentType("application/xml;charset=utf-8");
		resp.setCharacterEncoding("UTF-8");
		resp.getWriter().write(respMsg);
	}

}
